/* 定义中间部分的高度 */
(function(){
	var windowsHeight = $(window).height();
	var headerHeight = $('#headers').outerHeight(true);
	var footerHeight = $('#footers').outerHeight(true);
	var heightNum = windowsHeight-headerHeight-footerHeight;
	if( heightNum<600 ){ heightNum = 600 };
	$('#contentWamp').css('min-height', heightNum);
	$(window).resize(function(){
		windowsHeight = $(window).height();
		heightNum = windowsHeight-headerHeight-footerHeight;
		if( heightNum<600 ){ heightNum = 600 };
		$('#contentWamp').css('min-height', heightNum);
	})
})();

function onlyNum(val){
  if (val.length == 1) {
    val = val.replace(/[^1-9]/g, '');
  } else {
    val = val.replace(/\D/g, '').replace(/^0+/g, '')
  }
  if( isNaN(val) ){ return '' } // 防止复制粘贴非数字，出现NaN
  return val
}
function upload_Oss (btn) {
  var host = ''
  var policy = ''
  var dir = ''
  var expire = 0
  var accessid = ''
  var signature = ''
  var file_name = ''
  var dl_len = 0;
  var imgAll = []
  var pathArr = []
  var success_len = 0;
  var uploader = new plupload.Uploader({
    multi_selection: false, //是否可以在文件浏览对话框中选择多个文件，true为可以，false为不可以 
    browse_button: btn, //触发文件选择对话框的按钮，为那个元素id
    url: 'http://oss.aliyuncs.com', //服务器端的上传页面地址
    flash_swf_url: '../static/upload_lib/Moxie.swf', //swf文件，当需要使用swf方式进行上传时需要配置该参数
    silverlight_xap_url: '../static/upload_lib/Moxie.xap', //silverlight文件，当需要使用silverlight方式进行上传时需要配置该参数
    filters: {
      mime_types: [ //只允许上传图片
        { title: "Image files", extensions: "bmp,gif,jpg,png,jpeg" }
      ],
      max_file_size: 1024*5 +'kb', //最大只能上传1024*5kb的文件
      prevent_duplicates: false //不允许选取重复文件
    },
    init: {
      'PostInit': function(up) { //init初始化执行后的回调
        set_upload_param(up)
      },
      'BeforeUpload': function(up, file) { //文件开始上传之前的回调
        set_upload_param(up, file.name)
      },
      'FilesAdded': function(uploader, files) { //当文件添加到上传队列后触发
        files = files.slice(0)
        console.log(files)
        dl_len = files.length;
        uploader.is_addFile && uploader.is_addFile(files.length);
        files.forEach(function(item, i) {
          previewImage(item, function(imgsrc) {
            imgAll.push(imgsrc)
          })
        });
      },
      'FilesRemoved': function(uploader, files) { //当文件从上传队列移除后触发

      },
      'FileUploaded': function(uploader, file, response) { //文件上传成功的回调
        if (response.status == 200) {
          success_len++;
          pathArr.push(host + '/' + dir + file_name)
          if (success_len == dl_len) {
            uploader.fn && uploader.fn(pathArr);
            // console.log(success_len)
            success_len = 0;
          }
        }
      },
      'Error': function(uploader, err) { //发生错误的回调
        console.log(err)
        if( err.code == -600 ){
          layer.msg('不能选择大于5M的文件', {icon: 2}); return false 
        }
      }
    },
  });
  uploader.init();

  //获取签名请求
  function send_request(url) {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp != null) {
      xmlhttp.open("GET", url, false);
      xmlhttp.send(null);
      return JSON.parse(xmlhttp.responseText)
    } else {
      alert("Your browser does not support XMLHTTP.");
    }
  };

  //var signature_state = get_signature(expire);
  //验证签名是否失效，如果失效重新获取
  function get_signature(expire) {
    var now = Date.parse(new Date()) / 1000;
    if (expire < now + 3) { //3 为0.3s的缓冲时间
      // var data = send_request(getOssPolicyUrl + '/api/get_oss_info')
      var data = send_request('https://chain.51tuanli.com/api/get_oss_info')
      host = data.host;
      policy = data.policy;
      dir = data.dir;
      expire = data.expire;
      accessid = data.accessid;
      signature = data.signature;
      return true;
    }
    return false;
  };

  //随机文件名字
  function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  //获取图片后缀
  function get_suffix(filename) {
    var pos = filename.lastIndexOf('.')
    var suffix = ''
    if (pos != -1) {
      suffix = filename.substring(pos)
    }
    return suffix;
  }

  //动态配置上传参数
  function set_upload_param(up, filename) {
    var suffix = '';
    //验证签名
    get_signature(expire);
    //是否随机文件名
    if (filename != '' && filename) {
      // console.log(filename)
      suffix = get_suffix(filename)
      file_name = random_string(18) + suffix;
    } else {
      file_name = '${filename}';
    }
    var new_multipart_params = {
      'Filename': dir + file_name,
      'key': dir + file_name, //'${filename}'
      'policy': policy,
      'OSSAccessKeyId': accessid,
      'success_action_status': '200', //让服务端返回200,不然，默认会返回204
      'signature': signature,
    };
    up.setOption({
      'url': host,
      'multipart_params': new_multipart_params
    });
  }

  //删除单个待上传图片
  function removeFile(up, file, self) {
    up.removeFile(file);
    self.parentNode.parentNode.removeChild(self.parentNode);
    uploader.is_addFile && uploader.is_addFile(up.files.length, self.index);
  }

  //生成缩略图方法
  function previewImage(file, callback) {
    if (!file || !/image\//.test(file.type)) return; //确保文件是图片
    if (file.type == 'image/gif') { //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
      var fr = new mOxie.FileReader();
      fr.onload = function() {
        callback(fr.result);
        fr.destroy();
        fr = null;
      }
      fr.readAsDataURL(file.getSource());
    } else {
      var preloader = new mOxie.Image();
      preloader.onload = function() {
        preloader.downsize(300, 300); //先压缩一下要预览的图片,宽300，高300
        var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
        callback && callback(imgsrc); //callback传入的参数为预览图片的url
        preloader.destroy();
        preloader = null;
      };
      preloader.load(file.getSource());
    }
  }
  // return uploader;
  return {
    'events': uploader,
    'val': imgAll
  };
};